import { Component, OnInit, ElementRef, Renderer2, OnDestroy } from '@angular/core';
import { NavController, NavParams } from '@ionic/angular';
import { DataService } from '@services/data.service';
import { CacheService } from '@services/cache.service';

import { FireDetailPage } from '../../device/fire/fire-detail/fire-detail';
import { FireKagePage } from '../../device/fire/fire-link/fire-link';
import { FireOthersPage } from '../../device/fire/fire-others/fire-others';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';

@Component({
  selector: 'room-fire',
  templateUrl: 'fire.html',
  styleUrls: ['fire.scss']
})

export class RoomFirePage implements OnInit, OnDestroy {
  iconShow = true;
  sysName;
  projectId;          // 项目ID
  deviceSysId;        // 设备系统ID
  alarmInfos = [];         // 告警信息
  _refreshInterval;   // 页面刷新定时器
  autoScrollInterval = null;  // 告警消息定时器
  fireRoomData = {    // 参数点
    Total: 0,
    AlarmCount: 0,
    NormalCount: 0,
    BreakDownCount: 0
  };
  titles = [{
    type: 1,
    imgUrl: 'assets/imgs/fire/host.png',
    title: '消防主机',
    infos: [{ name: '监测点', value: 0, imgColor: '#222' }, { name: '正常点', value: 0, imgColor: '#25990e' },
    { name: '火警点', value: 0, imgColor: '#FF1919' }, { name: '故障点', value: 0, imgColor: '#ff8b02' }],
    infosDetail: []
  }, {
    type: 2,
    imgUrl: 'assets/imgs/fire/link.png',
    title: '联动控制柜',
    infos: [{ name: '监测点', value: 0, imgColor: '#222' }, { name: '正常点', value: 0, imgColor: '#25990e' },
    { name: '', value: '' }, { name: '故障点', value: 0, imgColor: '#ff8b02' }],
    infosDetail: []
  }, {
    type: 3,
    imgUrl: 'assets/imgs/fire/other.png',
    title: '其他',
    infos: [{ name: '监测点', value: 0, imgColor: '#222' }, { name: '正常点', value: 0, imgColor: '#25990e' },
    { name: '', value: '' }, { name: '告警点', value: 0, imgColor: '#ff8b02' }],
    infosDetail: []
  }];

  constructor(
    public navCtrl: NavController,
    public renderer: Renderer2,
    public el: ElementRef,
    public dataService: DataService,
    public activatedRoute: ActivatedRoute,
    public cacheService: CacheService
  ) {
    this.projectId = this.cacheService.currentProject.projectId ? this.cacheService.currentProject.projectId : 0;
    this.activatedRoute.queryParams.subscribe(params => {
      console.log(params)
      this.sysName = params.systemName ? params.systemName : '';
      this.iconShow = params.iconShow === 'false' ? false : true
      this.deviceSysId = params.systemId;
    });
  }

  ngOnInit() {

  }

  ionViewWillEnter() {
    const elements = document.querySelectorAll('ion-tab-bar');
    if (elements != null) {
      Object.keys(elements).map((key) => {
        elements[key].style.display = 'none';
      });
    }
    this.getFireParams(this.projectId);
  }

  ionViewWillLeave() {
    if (this._refreshInterval) {
      clearInterval(this._refreshInterval);
    }
  }

  // 获取房间及设备参数
  getFireParams(projectId) {
    this.dataService.getFireParams(projectId).subscribe(res => {
      if (res.data) {
        this.getGroupByType(res.data.data);
        this.dealFireData(projectId, res.data.data);
        this._refreshInterval = setInterval(() => {
          this.dealFireData(projectId, res.data.data);
        }, 10000)
      }
    });
  }

  dealFireData(projectId, params) {
    this.dataService.getFireAlarms(projectId).subscribe(data => {
      if (data.data && data.data.realTimeInfos) {
        this.getBasicData(data.data.realTimeInfos, params);
        this.getInitData(data.data.realTimeInfos, this.titles).subscribe(data => {
          this.titles = data;
        })
      } else {
        this.getBasicData([], params);
        this.getInitData([], this.titles).subscribe(data => {
          this.titles = data;
        })
      }
    })
  }

  // 按照设备类型进行分组
  getGroupByType(datas) {
    const data = {
      data1: [],
      data2: [],
      data3: []
    };
    for (const item of datas) {
      if (item.type === 1) {
        data.data1.push(item);
      } else if (item.type === 2) {
        data.data2.push(item);
      } else {
        data.data3.push(item);
      }
    }
    this.titles[0].infosDetail = data.data1;
    this.titles[1].infosDetail = data.data2;
    this.titles[2].infosDetail = data.data3;
    console.log('消防设备分组', this.titles)
  }

  // 获取房间基础数据总数计算
  getBasicData(data, datas) {
    const groups = {
      data1: [],
      data2: [],
    };
    for (const item of data) {
      item.dateTime = item.dateTime.substr(0, item.dateTime.length - 4);

      if (item.deviceDataType !== 3) {
        if (item.type === 1) {
          groups.data1.push(item);
        } else if (item.type === 2) {
          groups.data2.push(item);
        }
      }
    }
    let Total = 0, NormalTotal = 0, AlarmTotal = 0, BreakTotal = 0;
    for (const item of datas) {
      Total += item.deviceTotalCount
    }
    AlarmTotal = groups.data1.length;
    BreakTotal = groups.data2.length;
    NormalTotal = Total - AlarmTotal - BreakTotal;
    this.fireRoomData.Total = Total;
    this.fireRoomData.AlarmCount = AlarmTotal;
    this.fireRoomData.BreakDownCount = BreakTotal;
    this.fireRoomData.NormalCount = NormalTotal;
    this.alarmInfos = groups.data1;
    this.alarmInfos = this.alarmInfos.concat(groups.data2);
    this.autoScroll(this.alarmInfos.length);
  }

  // 设备实时数据整理
  getInitData(items, datas): Observable<any> {
    return new Observable(responseObserver => {
      this.getOthersAlarm().subscribe(res => {
        // 将各个设备数据放入对应的设备下
        for (const data of datas) {
          for (const dat of data.infosDetail) {
            dat.alarmNum = [];
            dat.breakNum = [];
            for (const item of items) {
              if (item.deviceDataType === dat.type && item.fireDeviceType === dat.fireDeviceType) {
                if (item.type === 1) {
                  dat.alarmNum.push(item);
                } else if (item.type === 2) {
                  dat.breakNum.push(item);
                }
              }
            }
            dat.alarmCount = dat.alarmNum.length;
            dat.breakDownCount = dat.breakNum.length;
            dat.normalCount = dat.deviceTotalCount - dat.alarmCount - dat.breakDownCount;
          }
        }

        // 获取其它告警信息
        for (const data of datas) {
          if (data.type === 3) {
            for (const dats of data.infosDetail) {
              dats.alarms = [];
              for (const dat of dats.deviceTypeList) {
                for (const item of res.data) {
                  if (item.alarmLevel === 3) {
                    item.type === 1;
                  } else if (item.alarmLevel === 2) {
                    item.type === 2;
                  }
                  item.dateTime = item.deviceValueLastTime.substr(0, item.deviceValueLastTime.length - 4);
                  item.content = item.alarmName;

                  if (item.deviceTypeId === dat.deviceTypeId && item.deviceParameterCode === dat.deviceParamId) {
                    dats.alarmNum.push(item);
                  }
                }
              }
              dats.alarmNum = this.unique(dats.alarmNum);
              dats.alarmCount = dats.alarmNum.length;
              dats.normalCount = dats.deviceTotalCount - dats.alarmCount - dats.breakDownCount;
              datas[2].infos[3].value += dats.alarmCount;
            }
          }
        }

        // 计算消防设备类型数据总数
        for (const data of datas) {
          // 处理设备类型为其它的告警点数据
          let alarmNum = 0;
          let breakNum = 0;
          let normalNum = 0;
          let totalNum = 0;
          for (const dat of data.infosDetail) {
            totalNum += dat.deviceTotalCount;
            normalNum += dat.normalCount;
            alarmNum += dat.alarmCount;
            breakNum += dat.breakDownCount;
          }
          data.infos[0].value = totalNum;
          data.infos[1].value = normalNum;
          data.infos[2].value = alarmNum;
          if (data.type === 3) {
            data.infos[3].value = alarmNum;
          } else {
            data.infos[3].value = breakNum;
          }
          if (data.type === 2 || data.type === 3) {
            data.infos[2].value = null;
          }

        }
        console.log('实时数据整理', datas);
        responseObserver.next(datas);
        responseObserver.complete();
      });
    });
  }


  unique(arr1) {
    const res = new Map();
    return arr1.filter((a) => !res.has(a.deviceId) && res.set(a.deviceId, 1))
  }

  getOthersAlarm(): Observable<any> {
    return new Observable(responseObserver => {
      this.dataService.getFireOtherAlarms(this.projectId).subscribe(res => {
        responseObserver.next(res);
        responseObserver.complete();
      })
    });
  }

  // 告警滚动
  autoScroll(len) {
    const step = -90;
    let top = 1;
    const ele = this.el.nativeElement.querySelector('.Text-init');
    if (this.autoScrollInterval) {
      clearInterval(this.autoScrollInterval);
      this.renderer.setStyle(ele, 'transition', 'unset');
      this.renderer.setStyle(ele, 'top', 0 + 'px');
    }
    this.autoScrollInterval = setInterval(() => {
      if (top < len) {
        this.renderer.setStyle(ele, 'top', top * step + 'px');
        if (top === 1) {
          this.renderer.setStyle(ele, 'transition', 'top 1s');
        }
        top++;
      } else {
        top = 0;
        this.renderer.setStyle(ele, 'transition', 'unset');
      }
    }, 2000);
  }

  // 跳转设备房间页
  toDetail(index) {
    if (index === 0) {
      this.navCtrl.navigateForward(['tabs/home/FireDetailPage'], {
        queryParams: {
          data: this.titles[0],
          projectId: this.projectId
        }
      });
    } else if (index === 1) {
      this.navCtrl.navigateForward(['tabs/home/FireKagePage'], {
        queryParams: {
          projectId: this.projectId,
        }
      });
    } else {
      this.navCtrl.navigateForward(['tabs/home/FireOthersPage'], {
        queryParams: {
          projectId: this.projectId,
        }
      });
    }
  }

  ngOnDestroy() {
    if (this._refreshInterval) {
      clearInterval(this._refreshInterval);
    }
  }
}
